import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import styled, { keyframes } from 'styled-components';
import { motion, AnimatePresence } from 'framer-motion';

// 背景星空动画
const twinkle = keyframes`
  0% { opacity: 0.2; }
  50% { opacity: 1; }
  100% { opacity: 0.2; }
`;

// 牌的翻转动画
const flip = keyframes`
  0% { transform: rotateY(0); }
  50% { transform: rotateY(90deg); }
  100% { transform: rotateY(0); }
`;

const DrawContainer = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #1a0a2e 0%, #0d0630 100%);
  color: white;
  padding: 20px;
  position: relative;
  overflow: hidden;
`;

const Star = styled.div`
  position: absolute;
  background-color: white;
  border-radius: 50%;
  animation: ${twinkle} ${(props) => props.duration || 3}s infinite ease-in-out;
`;

const Header = styled.h1`
  font-size: 2rem;
  margin-bottom: 20px;
  text-align: center;
  background: linear-gradient(to right, #9d4edd, #5a189a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
`;

const QuestionDisplay = styled.div`
  max-width: 800px;
  margin: 0 auto 30px;
  text-align: center;
  font-size: 1.2rem;
  color: #e0aaff;
  padding: 15px;
  background: rgba(90, 24, 154, 0.2);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(157, 78, 221, 0.3);
`;

const GuidanceText = styled.p`
  text-align: center;
  font-size: 1.1rem;
  color: #c77dff;
  margin-bottom: 30px;
`;

const CardsContainer = styled.div`
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 30px;
  margin: 40px 0;
  perspective: 1000px;
`;

const CardWrapper = styled(motion.div)`
  width: 120px;
  height: 200px;
  position: relative;
  cursor: pointer;
`;

const CardInner = styled.div`
  position: relative;
  width: 100%;
  height: 100%;
  transform-style: preserve-3d;
  transition: transform 0.8s;
  transform: ${(props) => props.isFlipped ? 'rotateY(180deg)' : 'rotateY(0)'};
`;

const CardFront = styled.div`
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  background: linear-gradient(135deg, #4b0082 0%, #8a2be2 100%);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3rem;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
`;

const CardBack = styled.div`
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  background: linear-gradient(135deg, #1a0a2e 0%, #0d0630 100%);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: rotateY(180deg);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
  color: #e0aaff;
  font-weight: bold;
  text-align: center;
  padding: 10px;
`;

const CardName = styled.div`
  font-size: 0.8rem;
  position: absolute;
  bottom: 10px;
  width: 100%;
  text-align: center;
`;

const ActionButton = styled(motion.button)`
  padding: 15px 40px;
  font-size: 1.1rem;
  border: none;
  border-radius: 50px;
  background: linear-gradient(45deg, #9d4edd, #5a189a);
  color: white;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(90, 24, 154, 0.3);
  margin: 30px auto;
  display: block;
  
  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 20px rgba(90, 24, 154, 0.5);
  }
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }
`;

const LoadingSpinner = styled.div`
  width: 50px;
  height: 50px;
  border: 5px solid rgba(157, 78, 221, 0.3);
  border-top: 5px solid #9d4edd;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 30px auto;
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
`;

const TarotDraw = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { question, category, spread } = location.state || { question: '', category: '', spread: null };
  
  const [cards, setCards] = useState([]);
  const [flippedCards, setFlippedCards] = useState([]);
  const [isDrawing, setIsDrawing] = useState(false);
  const [stars, setStars] = useState([]);
  const [guidanceText, setGuidanceText] = useState('请集中意念于你的问题...');

  // 生成随机星星背景
  useEffect(() => {
    const starsArray = [];
    for (let i = 0; i < 100; i++) {
      starsArray.push({
        id: i,
        top: `${Math.random() * 100}%`,
        left: `${Math.random() * 100}%`,
        size: `${Math.random() * 3 + 1}px`,
        duration: Math.random() * 3 + 2
      });
    }
    setStars(starsArray);
  }, []);

  // 模拟抽牌过程
  const drawCards = async () => {
    setIsDrawing(true);
    setGuidanceText('正在为你抽取塔罗牌...');
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 生成模拟的塔罗牌数据
    const mockCards = [];
    for (let i = 0; i < spread.cardCount; i++) {
      mockCards.push({
        id: i,
        name: `塔罗牌${i + 1}`,
        position: spread.positions[i] || `位置${i + 1}`,
        isReversed: Math.random() > 0.7,
        upright: '正位含义示例',
        reversed: '逆位含义示例'
      });
    }
    
    setCards(mockCards);
    setIsDrawing(false);
    setGuidanceText('点击牌面查看解读');
  };

  // 翻牌处理
  const flipCard = (index) => {
    if (!flippedCards.includes(index)) {
      setFlippedCards([...flippedCards, index]);
    }
  };

  // 检查是否所有牌都已翻开
  const allCardsFlipped = cards.length > 0 && flippedCards.length === cards.length;

  // 查看解读
  const handleViewInterpretation = () => {
    if (!allCardsFlipped) {
      alert('请先翻开所有塔罗牌');
      return;
    }
    
    // 导航到解读页面，传递牌阵信息
    navigate('/tarot/interpretation', { 
      state: { 
        question: question,
        category: category,
        spread: spread,
        cards: cards
      }
    });
  };

  // 组件加载时自动开始抽牌
  useEffect(() => {
    if (spread) {
      drawCards();
    }
  }, [spread]);

  return (
    <DrawContainer>
      {/* 星空背景 */}
      {stars.map(star => (
        <Star 
          key={star.id}
          style={{
            top: star.top,
            left: star.left,
            width: star.size,
            height: star.size
          }}
          duration={star.duration}
        />
      ))}
      
      <Header>塔罗牌占卜</Header>
      
      <QuestionDisplay>
        &quot;{question}&quot;
      </QuestionDisplay>
      
      <GuidanceText>{guidanceText}</GuidanceText>
      
      {isDrawing ? (
        <LoadingSpinner />
      ) : (
        <AnimatePresence>
          <CardsContainer>
            {cards.map((card, index) => (
              <CardWrapper
                key={index}
                initial={{ opacity: 0, y: 50 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.2 }}
                onClick={() => flipCard(index)}
              >
                <CardInner isFlipped={flippedCards.includes(index)}>
                  <CardFront>
                    ♣
                  </CardFront>
                  <CardBack>
                    {card.isReversed ? '逆位' : '正位'}
                    <CardName>{card.name}</CardName>
                  </CardBack>
                </CardInner>
              </CardWrapper>
            ))}
          </CardsContainer>
        </AnimatePresence>
      )}
      
      <ActionButton
        whileHover={{ scale: allCardsFlipped ? 1.05 : 1 }}
        whileTap={{ scale: allCardsFlipped ? 0.95 : 1 }}
        onClick={handleViewInterpretation}
        disabled={!allCardsFlipped}
      >
        {allCardsFlipped ? '查看解读' : '请先翻开所有塔罗牌'}
      </ActionButton>
    </DrawContainer>
  );
};

export default TarotDraw;